from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.responses import JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import os
import uuid
import shutil
import re
from datetime import datetime
from typing import List, Optional
import aiofiles
from pathlib import Path
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 导入数据库和模型
from database import (
    connect_to_mongo, 
    close_mongo_connection, 
    TaskService, 
    FileService
)
from models import Task, TaskCreate, TaskUpdate, FileMetadata

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    try:
        await connect_to_mongo()
        print("数据库连接成功")
    except Exception as e:
        print(f"启动时连接数据库失败: {e}")
    
    yield
    
    # 关闭时
    try:
        await close_mongo_connection()
        print("数据库连接已关闭")
    except Exception as e:
        print(f"关闭时断开数据库连接失败: {e}")

app = FastAPI(title="文件管理任务追踪API", version="1.0.0", lifespan=lifespan)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173", "http://localhost:3000", "*"],  # 允许前端域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置文件存储目录
UPLOAD_DIR = Path(os.getenv("UPLOAD_DIR", "public/uploads"))
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

# 配置静态文件服务
app.mount("/uploads", StaticFiles(directory=str(UPLOAD_DIR)), name="uploads")

# 文件大小限制
MAX_FILE_SIZE = int(os.getenv("MAX_FILE_SIZE", 52428800))  # 默认50MB

def serialize_task_for_response(task: Task) -> dict:
    """将Task对象序列化为可JSON化的字典"""
    task_dict = task.model_dump(by_alias=True)
    
    # 确保 id 字段正确设置
    if "_id" in task_dict:
        task_dict["id"] = task_dict.pop("_id")
    elif not task_dict.get("id"):
        raise ValueError("Task对象缺少必要的ID字段")
    
    # 确保日期字段正确序列化
    for field_name, field_value in task_dict.items():
        if isinstance(field_value, datetime):
            task_dict[field_name] = field_value.isoformat()
        elif field_name == 'attachments' and field_value:
            # 处理附件中的日期字段
            for attachment in field_value:
                if 'uploaded_at' in attachment and isinstance(attachment['uploaded_at'], datetime):
                    attachment['uploaded_at'] = attachment['uploaded_at'].isoformat()
    return task_dict

def is_allowed_file_type(filename: str, content_type: str) -> bool:
    """检查文件类型是否允许"""
    allowed_extensions = {'.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png', '.gif', '.xlsx', '.xls', '.txt', '.zip', '.rar'}
    allowed_mime_types = {
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'image/jpeg',
        'image/png',
        'image/gif',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain',
        'application/zip',
        'application/x-rar-compressed'
    }
    
    file_extension = Path(filename).suffix.lower()
    return file_extension in allowed_extensions or content_type in allowed_mime_types

def generate_safe_filename(original_filename: str) -> str:
    """生成安全的文件名"""
    # 获取文件扩展名
    file_extension = Path(original_filename).suffix
    # 获取文件名（不含扩展名）
    name_without_ext = Path(original_filename).stem
    # 生成唯一ID
    unique_id = str(uuid.uuid4())[:8]
    # 时间戳
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    # 安全的文件名
    safe_name = f"{timestamp}_{unique_id}_{name_without_ext}{file_extension}"
    return safe_name

@app.get("/")
async def root():
    return {"message": "文件管理任务追踪API服务正在运行", "version": "1.0.0"}

# ==================== 任务管理API ====================

@app.post("/api/tasks")
async def create_task(task_data: TaskCreate):
    """创建新任务"""
    try:
        task = await TaskService.create_task(task_data)
        return JSONResponse(content={
            "success": True,
            "message": "任务创建成功",
            "task": serialize_task_for_response(task)
        })
    except Exception as e:
        print(f"创建任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"任务创建失败: {str(e)}")

@app.get("/api/tasks")
async def get_all_tasks():
    """获取所有任务"""
    try:
        tasks = await TaskService.get_all_tasks()
        return JSONResponse(content={
            "success": True,
            "tasks": [serialize_task_for_response(task) for task in tasks]
        })
    except Exception as e:
        print(f"获取任务列表错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取任务列表失败: {str(e)}")

@app.get("/api/tasks/{task_id}")
async def get_task(task_id: str):
    """获取单个任务"""
    try:
        task = await TaskService.get_task(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        
        return JSONResponse(content={
            "success": True,
            "task": serialize_task_for_response(task)
        })
    except HTTPException:
        raise
    except Exception as e:
        print(f"获取任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取任务失败: {str(e)}")

@app.put("/api/tasks/{task_id}")
async def update_task(task_id: str, task_update: TaskUpdate):
    """更新任务"""
    try:
        task = await TaskService.update_task(task_id, task_update)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在或更新失败")
        
        return JSONResponse(content={
            "success": True,
            "message": "任务更新成功",
            "task": serialize_task_for_response(task)
        })
    except HTTPException:
        raise
    except Exception as e:
        print(f"更新任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"更新任务失败: {str(e)}")

@app.delete("/api/tasks/{task_id}")
async def delete_task(task_id: str):
    """删除任务"""
    try:
        # 先获取任务信息，获取附件列表
        task = await TaskService.get_task(task_id)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        
        # 删除任务相关的文件
        deleted_files = []
        failed_files = []
        task_folder_deleted = False
        
        if task.attachments:
            for attachment in task.attachments:
                try:
                                       
                    # 删除文件元数据
                    file_deleted = await FileService.delete_file_metadata(attachment.id)
                    if file_deleted:
                        deleted_files.append(attachment.name)
                        print(f"已删除文件元数据: {attachment.name}")
                    else:
                        failed_files.append(attachment.name)
                except Exception as e:
                    print(f"删除附件 {attachment.name} 失败: {e}")
                    failed_files.append(attachment.name)
        
        # 删除任务文件夹
        try:
            if task.folder_path:
                # 构建完整的文件夹路径
                folder_path = UPLOAD_DIR / task.folder_path
                print(f"尝试删除任务文件夹: {folder_path}")
                if folder_path.exists():
                    shutil.rmtree(folder_path)
                    task_folder_deleted = True
                    print(f"已删除任务文件夹: {folder_path}")
            
        except Exception as folder_error:
            print(f"删除任务文件夹失败: {folder_error}")
        except Exception as folder_error:
            print(f"删除任务文件夹失败: {folder_error}")
        
        # 删除任务记录
        success = await TaskService.delete_task(task_id)
        if not success:
            raise HTTPException(status_code=404, detail="任务删除失败")
        
        # 构建响应消息
        message = "任务删除成功"
        if deleted_files:
            message += f"，已删除关联文件: {', '.join(deleted_files)}"
        if task_folder_deleted:
            message += "，已删除任务文件夹"
        if failed_files:
            message += f"，以下文件删除失败: {', '.join(failed_files)}"
        
        return JSONResponse(content={
            "success": True,
            "message": message,
            "deleted_files": deleted_files,
            "failed_files": failed_files,
            "folder_deleted": task_folder_deleted
        })
    except HTTPException:
        raise
    except Exception as e:
        print(f"删除任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"删除任务失败: {str(e)}")

@app.get("/api/tasks/status/{status}")
async def get_tasks_by_status(status: str):
    """根据状态获取任务"""
    try:
        tasks = await TaskService.get_tasks_by_status(status)
        return JSONResponse(content={
            "success": True,
            "tasks": [serialize_task_for_response(task) for task in tasks]
        })
    except Exception as e:
        print(f"根据状态获取任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取任务失败: {str(e)}")

@app.get("/api/tasks/category/{category}")
async def get_tasks_by_category(category: str):
    """根据分类获取任务"""
    try:
        tasks = await TaskService.get_tasks_by_category(category)
        return JSONResponse(content={
            "success": True,
            "tasks": [serialize_task_for_response(task) for task in tasks]
        })
    except Exception as e:
        print(f"根据分类获取任务错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取任务失败: {str(e)}")

# ==================== 文件管理API ====================

@app.post("/api/upload")
async def upload_file(
    file: UploadFile = File(...),
    folder_path: Optional[str] = Form(None)
):
    """上传单个文件"""
    try:
        # 检查文件类型
        if not is_allowed_file_type(file.filename, file.content_type):
            raise HTTPException(
                status_code=400, 
                detail=f"不支持的文件类型: {file.content_type}"
            )
        
        # 检查文件大小（限制为50MB）
        file_size = 0
        content = await file.read()
        file_size = len(content)
        
        if file_size > MAX_FILE_SIZE:
            raise HTTPException(
                status_code=400,
                detail="文件大小不能超过50MB"
            )
        
        # 生成安全文件名
        safe_filename = generate_safe_filename(file.filename)
        
        # 确定保存路径
        if folder_path:
            save_dir = UPLOAD_DIR / folder_path
        else:
            # 默认按日期分组
            date_folder = datetime.now().strftime("%Y-%m")
            save_dir = UPLOAD_DIR / date_folder
        
        save_dir.mkdir(parents=True, exist_ok=True)
        file_path = save_dir / safe_filename
        
        # 保存文件
        async with aiofiles.open(file_path, 'wb') as f:
            await f.write(content)
        
        # 生成文件URL
        relative_path = file_path.relative_to(UPLOAD_DIR)
        file_url = f"/uploads/{relative_path.as_posix()}"
        
        # 保存文件元数据到MongoDB
        file_metadata = FileMetadata(
            original_name=file.filename,
            safe_filename=safe_filename,
            content_type=file.content_type,
            size=file_size,
            file_path=str(file_path),
            file_url=file_url,
            folder_path=folder_path
        )
        
        saved_file = await FileService.save_file_metadata(file_metadata)
        
        # 确保使用正确的ID（从数据库返回的实际ID）
        file_id = saved_file.id if saved_file.id else str(uuid.uuid4())
        print(f"文件上传成功 - ID: {file_id}, saved_file.id: {saved_file.id}, 文件名: {file.filename}")
        
        return JSONResponse(content={
            "success": True,
            "message": "文件上传成功",
            "file": {
                "id": file_id,
                "name": file.filename,
                "type": file.content_type,
                "size": file_size,
                "url": file_url,
                "uploaded_at": saved_file.uploaded_at.isoformat()
            }
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件上传错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")

@app.post("/api/upload-multiple")
async def upload_multiple_files(
    files: List[UploadFile] = File(...),
    folder_path: Optional[str] = Form(None)
):
    """批量上传文件"""
    uploaded_files = []
    errors = []
    
    for file in files:
        try:
            # 检查文件类型
            if not is_allowed_file_type(file.filename, file.content_type):
                errors.append(f"{file.filename}: 不支持的文件类型")
                continue
            
            # 检查文件大小
            content = await file.read()
            file_size = len(content)
            
            if file_size > MAX_FILE_SIZE:
                errors.append(f"{file.filename}: 文件大小超过50MB")
                continue
            
            # 生成安全文件名
            safe_filename = generate_safe_filename(file.filename)
            
            # 确定保存路径
            if folder_path:
                save_dir = UPLOAD_DIR / folder_path
            else:
                date_folder = datetime.now().strftime("%Y-%m")
                save_dir = UPLOAD_DIR / date_folder
            
            save_dir.mkdir(parents=True, exist_ok=True)
            file_path = save_dir / safe_filename
            
            # 保存文件
            async with aiofiles.open(file_path, 'wb') as f:
                await f.write(content)
            
            # 生成文件URL
            relative_path = file_path.relative_to(UPLOAD_DIR)
            file_url = f"/uploads/{relative_path.as_posix()}"
            
            # 保存文件元数据到MongoDB
            file_metadata = FileMetadata(
                original_name=file.filename,
                safe_filename=safe_filename,
                content_type=file.content_type,
                size=file_size,
                file_path=str(file_path),
                file_url=file_url,
                folder_path=folder_path
            )
            
            saved_file = await FileService.save_file_metadata(file_metadata)
            
            uploaded_files.append({
                "id": saved_file.id,
                "name": file.filename,
                "type": file.content_type,
                "size": file_size,
                "url": file_url,
                "uploaded_at": saved_file.uploaded_at.isoformat()
            })
            
        except Exception as e:
            errors.append(f"{file.filename}: {str(e)}")
    
    return JSONResponse(content={
        "success": len(uploaded_files) > 0,
        "message": f"成功上传 {len(uploaded_files)} 个文件",
        "files": uploaded_files,
        "errors": errors
    })

@app.delete("/api/files/{file_id}")
async def delete_file(file_id: str):
    """删除文件"""
    try:
        print(f"尝试删除文件，file_id: {file_id}")
        
        # 首先尝试直接查找
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            print(f"直接查找失败，尝试查找所有文件记录...")
            
            # 调试：列出所有文件记录
            from database import database
            import os
            
            collection = database.database[os.getenv("FILES_COLLECTION", "files")]
            cursor = collection.find({})
            
            print("数据库中的所有文件记录：")
            async for file_data in cursor:
                print(f"  _id: {file_data.get('_id')}, id: {file_data.get('id')}, name: {file_data.get('original_name')}")
            
            print(f"文件不存在于数据库中: {file_id}")
            raise HTTPException(status_code=404, detail="文件不存在")
        
        print(f"找到文件元数据: {file_metadata.original_name}")
        
        # 删除物理文件
        file_path = Path(file_metadata.file_path)
        if file_path.exists():
            file_path.unlink()
            print(f"物理文件已删除: {file_metadata.file_path}")
        else:
            print(f"物理文件不存在: {file_metadata.file_path}")
        
        # 删除数据库记录
        success = await FileService.delete_file_metadata(file_id)
        if not success:
            print(f"删除数据库记录失败: {file_id}")
            raise HTTPException(status_code=500, detail="删除文件记录失败")
        
        print(f"文件删除成功: {file_id}")
        return JSONResponse(content={
            "success": True,
            "message": "文件删除成功"
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件删除错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件删除失败: {str(e)}")

@app.get("/api/files")
async def list_files():
    """获取所有文件列表"""
    try:
        files_metadata = await FileService.get_all_files()
        files = []
        
        for file_meta in files_metadata:
            # 检查文件是否仍然存在
            file_path = Path(file_meta.file_path)
            if file_path.exists():
                files.append({
                    "id": file_meta.id,
                    "name": file_meta.original_name,
                    "type": file_meta.content_type,
                    "size": file_meta.size,
                    "url": file_meta.file_url,
                    "uploaded_at": file_meta.uploaded_at.isoformat()
                })
        
        return JSONResponse(content={
            "success": True,
            "files": files
        })
        
    except Exception as e:
        print(f"获取文件列表错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")

@app.get("/api/files/{file_id}")
async def get_file_info(file_id: str):
    """获取文件信息"""
    try:
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            raise HTTPException(status_code=404, detail="文件不存在")
        
        file_path = Path(file_metadata.file_path)
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件已被删除")
        
        return JSONResponse(content={
            "success": True,
            "file": {
                "id": file_metadata.id,
                "name": file_metadata.original_name,
                "type": file_metadata.content_type,
                "size": file_metadata.size,
                "url": file_metadata.file_url,
                "uploaded_at": file_metadata.uploaded_at.isoformat()
            }
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"获取文件信息错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取文件信息失败: {str(e)}")

@app.get("/api/download/{file_id}")
async def download_file(file_id: str):
    """下载文件"""
    try:
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            raise HTTPException(status_code=404, detail="文件不存在")
        
        file_path = Path(file_metadata.file_path)
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件已被删除")
        
        return FileResponse(
            path=str(file_path),
            filename=file_metadata.original_name,
            media_type=file_metadata.content_type
        )
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件下载错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件下载失败: {str(e)}")

# ==================== 调试API ====================

@app.get("/api/debug/folders")
async def debug_folders():
    """调试：显示上传文件夹结构"""
    try:
        folder_structure = {}
        tasks_dir = UPLOAD_DIR / "tasks"
        
        if tasks_dir.exists():
            for folder in tasks_dir.iterdir():
                if folder.is_dir():
                    files = []
                    for file in folder.iterdir():
                        if file.is_file():
                            files.append({
                                "name": file.name,
                                "size": file.stat().st_size,
                                "modified": datetime.fromtimestamp(file.stat().st_mtime).isoformat()
                            })
                    folder_structure[folder.name] = {
                        "file_count": len(files),
                        "files": files
                    }
        
        return JSONResponse(content={
            "success": True,
            "upload_dir": str(UPLOAD_DIR),
            "tasks_dir": str(tasks_dir),
            "folder_structure": folder_structure
        })
    except Exception as e:
        return JSONResponse(content={
            "success": False,
            "error": str(e)
        }, status_code=500)

# ==================== 文件管理API ====================

@app.post("/api/upload")
async def upload_file(
    file: UploadFile = File(...),
    folder_path: Optional[str] = Form(None)
):
    """上传单个文件"""
    try:
        # 检查文件类型
        if not is_allowed_file_type(file.filename, file.content_type):
            raise HTTPException(
                status_code=400, 
                detail=f"不支持的文件类型: {file.content_type}"
            )
        
        # 检查文件大小（限制为50MB）
        file_size = 0
        content = await file.read()
        file_size = len(content)
        
        if file_size > MAX_FILE_SIZE:
            raise HTTPException(
                status_code=400,
                detail="文件大小不能超过50MB"
            )
        
        # 生成安全文件名
        safe_filename = generate_safe_filename(file.filename)
        
        # 确定保存路径
        if folder_path:
            save_dir = UPLOAD_DIR / folder_path
        else:
            # 默认按日期分组
            date_folder = datetime.now().strftime("%Y-%m")
            save_dir = UPLOAD_DIR / date_folder
        
        save_dir.mkdir(parents=True, exist_ok=True)
        file_path = save_dir / safe_filename
        
        # 保存文件
        async with aiofiles.open(file_path, 'wb') as f:
            await f.write(content)
        
        # 生成文件URL
        relative_path = file_path.relative_to(UPLOAD_DIR)
        file_url = f"/uploads/{relative_path.as_posix()}"
        
        # 保存文件元数据到MongoDB
        file_metadata = FileMetadata(
            original_name=file.filename,
            safe_filename=safe_filename,
            content_type=file.content_type,
            size=file_size,
            file_path=str(file_path),
            file_url=file_url,
            folder_path=folder_path
        )
        
        saved_file = await FileService.save_file_metadata(file_metadata)
        
        # 确保使用正确的ID（从数据库返回的实际ID）
        file_id = saved_file.id if saved_file.id else str(uuid.uuid4())
        print(f"文件上传成功 - ID: {file_id}, saved_file.id: {saved_file.id}, 文件名: {file.filename}")
        
        return JSONResponse(content={
            "success": True,
            "message": "文件上传成功",
            "file": {
                "id": file_id,
                "name": file.filename,
                "type": file.content_type,
                "size": file_size,
                "url": file_url,
                "uploaded_at": saved_file.uploaded_at.isoformat()
            }
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件上传错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")

@app.post("/api/upload-multiple")
async def upload_multiple_files(
    files: List[UploadFile] = File(...),
    folder_path: Optional[str] = Form(None)
):
    """批量上传文件"""
    uploaded_files = []
    errors = []
    
    for file in files:
        try:
            # 检查文件类型
            if not is_allowed_file_type(file.filename, file.content_type):
                errors.append(f"{file.filename}: 不支持的文件类型")
                continue
            
            # 检查文件大小
            content = await file.read()
            file_size = len(content)
            
            if file_size > MAX_FILE_SIZE:
                errors.append(f"{file.filename}: 文件大小超过50MB")
                continue
            
            # 生成安全文件名
            safe_filename = generate_safe_filename(file.filename)
            
            # 确定保存路径
            if folder_path:
                save_dir = UPLOAD_DIR / folder_path
            else:
                date_folder = datetime.now().strftime("%Y-%m")
                save_dir = UPLOAD_DIR / date_folder
            
            save_dir.mkdir(parents=True, exist_ok=True)
            file_path = save_dir / safe_filename
            
            # 保存文件
            async with aiofiles.open(file_path, 'wb') as f:
                await f.write(content)
            
            # 生成文件URL
            relative_path = file_path.relative_to(UPLOAD_DIR)
            file_url = f"/uploads/{relative_path.as_posix()}"
            
            # 保存文件元数据到MongoDB
            file_metadata = FileMetadata(
                original_name=file.filename,
                safe_filename=safe_filename,
                content_type=file.content_type,
                size=file_size,
                file_path=str(file_path),
                file_url=file_url,
                folder_path=folder_path
            )
            
            saved_file = await FileService.save_file_metadata(file_metadata)
            
            uploaded_files.append({
                "id": saved_file.id,
                "name": file.filename,
                "type": file.content_type,
                "size": file_size,
                "url": file_url,
                "uploaded_at": saved_file.uploaded_at.isoformat()
            })
            
        except Exception as e:
            errors.append(f"{file.filename}: {str(e)}")
    
    return JSONResponse(content={
        "success": len(uploaded_files) > 0,
        "message": f"成功上传 {len(uploaded_files)} 个文件",
        "files": uploaded_files,
        "errors": errors
    })

@app.delete("/api/files/{file_id}")
async def delete_file(file_id: str):
    """删除文件"""
    try:
        print(f"尝试删除文件，file_id: {file_id}")
        
        # 首先尝试直接查找
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            print(f"直接查找失败，尝试查找所有文件记录...")
            
            # 调试：列出所有文件记录
            from database import database
            import os
            
            collection = database.database[os.getenv("FILES_COLLECTION", "files")]
            cursor = collection.find({})
            
            print("数据库中的所有文件记录：")
            async for file_data in cursor:
                print(f"  _id: {file_data.get('_id')}, id: {file_data.get('id')}, name: {file_data.get('original_name')}")
            
            print(f"文件不存在于数据库中: {file_id}")
            raise HTTPException(status_code=404, detail="文件不存在")
        
        print(f"找到文件元数据: {file_metadata.original_name}")
        
        # 删除物理文件
        file_path = Path(file_metadata.file_path)
        if file_path.exists():
            file_path.unlink()
            print(f"物理文件已删除: {file_metadata.file_path}")
        else:
            print(f"物理文件不存在: {file_metadata.file_path}")
        
        # 删除数据库记录
        success = await FileService.delete_file_metadata(file_id)
        if not success:
            print(f"删除数据库记录失败: {file_id}")
            raise HTTPException(status_code=500, detail="删除文件记录失败")
        
        print(f"文件删除成功: {file_id}")
        return JSONResponse(content={
            "success": True,
            "message": "文件删除成功"
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件删除错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件删除失败: {str(e)}")

@app.get("/api/files")
async def list_files():
    """获取所有文件列表"""
    try:
        files_metadata = await FileService.get_all_files()
        files = []
        
        for file_meta in files_metadata:
            # 检查文件是否仍然存在
            file_path = Path(file_meta.file_path)
            if file_path.exists():
                files.append({
                    "id": file_meta.id,
                    "name": file_meta.original_name,
                    "type": file_meta.content_type,
                    "size": file_meta.size,
                    "url": file_meta.file_url,
                    "uploaded_at": file_meta.uploaded_at.isoformat()
                })
        
        return JSONResponse(content={
            "success": True,
            "files": files
        })
        
    except Exception as e:
        print(f"获取文件列表错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")

@app.get("/api/files/{file_id}")
async def get_file_info(file_id: str):
    """获取文件信息"""
    try:
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            raise HTTPException(status_code=404, detail="文件不存在")
        
        file_path = Path(file_metadata.file_path)
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件已被删除")
        
        return JSONResponse(content={
            "success": True,
            "file": {
                "id": file_metadata.id,
                "name": file_metadata.original_name,
                "type": file_metadata.content_type,
                "size": file_metadata.size,
                "url": file_metadata.file_url,
                "uploaded_at": file_metadata.uploaded_at.isoformat()
            }
        })
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"获取文件信息错误: {e}")
        raise HTTPException(status_code=500, detail=f"获取文件信息失败: {str(e)}")

@app.get("/api/download/{file_id}")
async def download_file(file_id: str):
    """下载文件"""
    try:
        file_metadata = await FileService.get_file_metadata(file_id)
        if not file_metadata:
            raise HTTPException(status_code=404, detail="文件不存在")
        
        file_path = Path(file_metadata.file_path)
        if not file_path.exists():
            raise HTTPException(status_code=404, detail="文件已被删除")
        
        return FileResponse(
            path=str(file_path),
            filename=file_metadata.original_name,
            media_type=file_metadata.content_type
        )
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"文件下载错误: {e}")
        raise HTTPException(status_code=500, detail=f"文件下载失败: {str(e)}")

# 调试API - 查看数据库中的文件记录
@app.get("/api/debug/files")
async def debug_list_files():
    """调试：查看数据库中的原始文件记录"""
    try:
        from database import database
        import os
        
        collection = database.database[os.getenv("FILES_COLLECTION", "files")]
        cursor = collection.find({})
        
        files = []
        async for file_data in cursor:
            # 保留原始数据结构
            files.append({
                "_id": file_data.get("_id"),
                "id": file_data.get("id"),
                "original_name": file_data.get("original_name"),
                "safe_filename": file_data.get("safe_filename"),
                "content_type": file_data.get("content_type"),
                "size": file_data.get("size"),
                "file_path": file_data.get("file_path"),
                "file_url": file_data.get("file_url"),
                "folder_path": file_data.get("folder_path"),
                "uploaded_at": file_data.get("uploaded_at"),
                "task_id": file_data.get("task_id")
            })
        
        return JSONResponse(content={
            "success": True,
            "total_files": len(files),
            "files": files
        })
        
    except Exception as e:
        print(f"调试获取文件列表错误: {e}")
        raise HTTPException(status_code=500, detail=f"调试获取文件列表失败: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
